<template>
  <div class="mod-supplier-supplier">
    <div class="search-bar">
      <!-- native modifier has been removed, please confirm whether the function has been affected  -->
      <el-form
        ref="searchFormRef"
        :inline="true"
        class="search-form"
        :model="searchForm"
        label-width="auto"

        @submit.prevent
      >
        <div class="input-row">
          <el-form-item
            prop="supplierName"
            :label="$t('shop.supplierName')+':'"
          >
            <el-input
              v-model="searchForm.supplierName"

              type="text"
              clearable
              :placeholder="$t('shop.supplierName')"
            />
          </el-form-item>
          <el-form-item
            prop="contactName"
            :label="$t('shop.contactName')+':'"
          >
            <el-input
              v-model="searchForm.contactName"

              type="text"
              clearable
              :placeholder="$t('shop.contactName')"
            />
          </el-form-item>
          <el-form-item
            prop="contactTel"
            :label="$t('shop.contactTel')+':'"
          >
            <el-input
              v-model="searchForm.contactTel"

              type="text"
              clearable
              :placeholder="$t('shop.contactTel')"
            />
          </el-form-item>
          <el-form-item
            prop="status"
            :label="$t('product.supplierStatus')+':'"
          >
            <el-select
              v-model="searchForm.status"

              clearable
              :placeholder="$t('tip.select')"
            >
              <el-option
                v-for="item in options"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            prop="supplierProdCount"
            :label="$t('shop.supplierCategoryName')+':'"
          >
            <el-select
              v-model="searchForm.supplierCategoryId"

              clearable
              :placeholder="$t('tip.select')"
            >
              <el-option
                v-for="category in categoryList"
                :key="category.supplierCategoryId"
                :label="category.name"
                :value="category.supplierCategoryId"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <div
              class="default-btn primary-btn"
              @click="onSearch(true)"
            >
              {{ $t('crud.searchBtn') }}
            </div>
            <div
              class="default-btn"
              @click="resetForm('searchForm')"
            >
              {{ $t('shop.resetMap') }}
            </div>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="main-container">
      <div class="operation-bar">
        <div
          v-if="isAuth('supplier:supplier:save')"
          class="default-btn primary-btn"
          @click="onAddOrUpdate()"
        >
          {{ $t("crud.addTitle") }}
        </div>
        <div
          class="default-btn"
          @click.stop="getUpload()"
        >
          {{ $t('order.ImportingFiles') }}
        </div>
        <div
          v-if="isAuth('supplier:supplier:export')"
          class="default-btn"
          @click="getExportExcel()"
        >
          {{ $t('order.ExportingFiles') }}
        </div>
      </div>
      <div class="table-con">
        <el-table
          :data="dataList"
          header-cell-class-name="table-header"
          row-class-name="table-row-low"
          style="width: 100%"
        >
          <el-table-column
            :label="$t('shop.supplierName')"
            prop="supplierName"
            align="left"
            width="390"
          >
            <template #default="scope">
              <span class="table-cell-text line-clamp-one">{{ scope.row.supplierName || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('shop.supplierCategoryName')"
            prop="supplierCategoryName"
            align="left"
            width="230"
          >
            <template #default="scope">
              <span class="table-cell-text line-clamp-one">{{ scope.row.categoryName || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('shop.tel')"
            prop="tel"
            align="left"
            width="230"
          >
            <template #default="scope">
              <span class="table-cell-text line-clamp-one">{{ scope.row.tel || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('shop.contactName')"
            prop="contactName"
            align="left"
          >
            <template #default="scope">
              <span class="table-cell-text line-clamp-one">{{ scope.row.contactName || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('shop.contactTel')"
            prop="contactTel"
            align="left"
            width="110"
          >
            <template #default="scope">
              <span class="table-cell-text line-clamp-one">{{ scope.row.contactTel || '-' }}</span>
            </template>
          </el-table-column>
          <el-table-column
            :label="$t('product.status')"
            prop="status"
            align="center"
          >
            <template #default="scope">
              <span
                v-if="scope.row.status === 0"
                class="table-cell-text line-clamp-one"
              >{{ $t("publics.disable") }}</span>
              <span
                v-if="scope.row.status === 1"
                class="table-cell-text line-clamp-one"
              >{{ $t("shop.ena") }}</span>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            align="center"
            :label="$t('crud.menu')"
            width="220"
          >
            <template #default="scope">
              <div class="text-btn-con">
                <div
                  v-if="isAuth('supplier:supplier:update')"
                  class="default-btn text-btn"
                  @click="onAddOrUpdate(scope.row.supplierId)"
                >
                  {{ $t('temp.modify') }}
                </div>
                <div
                  v-if="isAuth('supplier:prod:edit') && scope.row.status === 1 && scope.row.isDefault !== 1"
                  class="default-btn text-btn"
                  @click="onAddOrUpdateProd(scope.row.supplierId,scope.row.supplierName)"
                >
                  {{ $t('shop.editProd') }}
                </div>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-pagination
        :current-page="page.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="page.pageSize"
        :total="page.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="onPageSizeChange"
        @current-change="onPageChange"
      />
    </div>
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdateRef"
      @refresh-data-list="refreshChange"
      @refresh-category-list="listCategory()"
    />
    <supplier-upload
      v-if="uploadVisible"
      ref="supplierUploadRef"
      @refresh-data-list="getWaitingExcel"
    />
  </div>
</template>

<script setup>

import { ElMessageBox, ElLoading } from 'element-plus'
import { isAuth } from '@/utils'
import AddOrUpdate from './components/supplier-add-or-update.vue'
import SupplierUpload from './components/supplier-upload.vue'

const Router = useRouter()
let tempSearchForm = null // 保存上次点击查询的请求条件

const dataList = ref([])
const categoryList = ref([])
const options = [{
  value: 0,
  label: '禁用'
}, {
  value: 1,
  label: '启用'
}]
const page = reactive({
  total: 0, // 总页数
  currentPage: 1, // 当前页数
  pageSize: 10 // 每页显示多少条
})
const searchForm = reactive({
  supplierName: '',
  contactName: '',
  contactTel: '',
  status: '', // 状态 0禁用 1启用
  supplierCategoryId: null
}) // 搜索
const addOrUpdateVisible = ref(false)
const uploadVisible = ref(false)
onMounted(() => {
  getDataList(page)
  listCategory()
})

const getDataList = (pageParam, newData = false) => {
  if (newData || !tempSearchForm) {
    tempSearchForm = JSON.parse(JSON.stringify(searchForm))
  }
  http({
    url: http.adornUrl('/supplier/supplier/page'),
    method: 'get',
    params: http.adornParams(
      Object.assign(
        {
          current: pageParam == null ? page.currentPage : pageParam.currentPage,
          size: pageParam == null ? page.pageSize : pageParam.pageSize
        },
        tempSearchForm
      )
    )
  }).then(({ data }) => {
    dataList.value = data.records
    page.total = data.total
  })
}
// 新增 / 修改
const addOrUpdateRef = ref(null)
const onAddOrUpdate = (id) => {
  addOrUpdateVisible.value = true
  nextTick(() => {
    addOrUpdateRef.value?.init(id)
  })
}
// 编辑供应商商品
const onAddOrUpdateProd = (id, name) => {
  Router.push({
    path: '/stock/supplier/new-prod',
    query: {
      supplierId: id,
      supplierName: name
    }
  })
}
const getWaitingExcel = () => {
  getDataList(page)
}
// 跳转至导入选择
const supplierUploadRef = ref(null)
const getUpload = () => {
  uploadVisible.value = true
  nextTick(() => {
    supplierUploadRef.value?.init()
  })
}
const getExportExcel = () => {
  ElMessageBox.confirm(`${$t('shop.exportTip')}`, $t('text.tips'), {
    confirmButtonText: $t('crud.filter.submitBtn'),
    cancelButtonText: $t('crud.filter.cancelBtn'),
    type: 'warning'
  }).then(() => {
    const loading = ElLoading.service({
      lock: true,
      target: '.mod-supplier-supplier',
      customClass: 'export-load',
      background: 'transparent',
      text: $t('formData.exportIng')
    })
    http({
      url: http.adornUrl('/supplier/supplier/exportSupplier'),
      method: 'get',
      params: http.adornParams(searchForm),
      responseType: 'blob' // 解决文件下载乱码问题
    }).then(({ data }) => {
      loading.close()
      const blob = new Blob([data], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8' })
      const fileName = $t('shop.comInfoSorXls')
      const elink = document.createElement('a')
      if ('download' in elink) { // 非IE下载
        elink.download = fileName
        elink.style.display = 'none'
        elink.href = URL.createObjectURL(blob)
        document.body.appendChild(elink)
        elink.click()
        URL.revokeObjectURL(elink.href) // 释放URL 对象
        document.body.removeChild(elink)
      } else { // IE10+下载
        navigator.msSaveBlob(blob, fileName)
      }
    }).catch((e) => {
      loading.close()
    })
  })
}
const listCategory = () => {
  http({
    url: http.adornUrl('/supplier/supplierCategory/list'),
    method: 'get',
    params: {
      isAll: 0
    }
  }).then(({ data }) => {
    categoryList.value = data
  })
}
/**
   * 刷新回调
   */
const refreshChange = () => {
  getDataList(page)
}
const onSearch = (newData = false) => {
  getDataList(page, newData)
}
const onPageSizeChange = (val) => {
  page.pageSize = val
  getDataList(page)
}
const onPageChange = (val) => {
  page.currentPage = val
  getDataList(page)
}
const searchFormRef = ref(null)
const resetForm = () => {
  searchFormRef.value?.resetFields()
  searchForm.supplierCategoryId = null
}

</script>
<style lang="scss" scoped>

</style>
